package com.docker.sys.role.roleMenu;

import com.docker.core.mvc.service.BaseService;
import com.docker.sys.menu.MenuService;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Okv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import kit.docker.convert.RecordKit;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author ldl
 * @Create 2020/09/23 023 11:26
 */
public class RoleMenuService extends BaseService {

    @Inject
    private RoleMenuDao roleMenuDao;

    @Inject
    private MenuService menuService;

    public List<Record> tree(String appId, boolean isSpAdmin, String roleId) {
        List<Record> menus;
        Okv cond = Okv.create()
                .set("m.app_id = ", appId)
                .set("m.status_flag = ", "1");
        if (isSpAdmin) {
            menus = menuService.list(Okv.by("cond", cond));
        } else {
            cond.set("rm.role_id = ", roleId);
            menus = roleMenuDao.list(Okv.by("cond", cond));
        }
        return menuService.buildTree(menus);
    }

    public List<Record> tree(String roleId, String appId) {
        List<Record> menus = roleMenuDao.tree(roleId, appId);
        List<Record> tree = new ArrayList<>();
        for (Record menu : menus) {
            if (StrKit.isBlank(menu.getStr("menu_pid")) && menu.getInt("menu_level") == 1) {
                getSonMenu(menu, menus);
                tree.add(menu);
            }
        }
        return tree;
    }

    private Record getSonMenu(Record parnetMenu, List<Record> menus) {
        List<Record> sonList = new ArrayList<>();
        for (Record menu : menus) {
            if (StrKit.notBlank(menu.getStr("menu_pid")) && menu.getStr("menu_pid").equals(parnetMenu.getStr("menu_id"))) {
                Record sonMenus = getSonMenu(menu, menus);
                sonList.add(sonMenus);
            }
        }
        parnetMenu.set("children", sonList);
        return parnetMenu;
    }

    public List<String> now(String roleId, String appId) {
        List<Record> roleMenus = roleMenuDao.now(roleId, appId);
        List<String> now = new ArrayList<>();
        for (Record roleMenu : roleMenus) {
            now.add(roleMenu.getStr("menu_id"));
        }
        return now;
    }

    public boolean save(String roleId, String menuIds) {

        roleMenuDao.deleteByRoleId(roleId);
        if (StrKit.isBlank(menuIds)) {
            return true;
        }
        String[] menuIdArr = menuIds.split(",");
        for (String menuId : menuIdArr) {
            roleMenuDao.save(RecordKit.objectToRecord(new RoleMenuBean(getUUID32(), roleId, menuId)));
        }

        return true;
    }

    public boolean delete(String roleId, String menuId) {
        roleMenuDao.delete(roleId, menuId);
        return true;
    }

}
